package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.LagouCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Date;


/**
 * @Author: Tao Zheng
 * @classNmae: LagouCodeServiceImpl
 * @packageName: com.lagou.edu.service.impl
 * @description:
 * @DATE: 2021/9/8 16:47
 */
@Service
public class LagouCodeServiceImpl implements LagouCodeService {

    @Autowired
    private LagouAuthCodeDao authCodeDao;

    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createAuthCode(String email, String code) {

        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000;

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreateTime(new Date(createTime));
        lagouAuthCode.setExpireTime(new Date(expireTime));

        authCodeDao.save(lagouAuthCode);
    }

    @Override
    public int validateCode(String email, String code) {
        LagouAuthCode authCode = authCodeDao.findFirstByEmailOrderByIdDesc(email);

        //1:正确，2:错误，0:超时
        if (authCode == null){
            return 2;
        }
        if (!authCode.getCode().equalsIgnoreCase(code)){
            return 2;
        }

        long expireTime = authCode.getExpireTime().getTime();
        if (expireTime <= System.currentTimeMillis()){
            return 0;
        }
        return 1;
    }
}
